package interviewClassic150;

import org.junit.Test;

import java.util.*;

public class ThreeSum {
    public List<List<Integer>> threeSum(int[] nums) {
        //结果集
        List<List<Integer>> res = new ArrayList<>();
        int n = nums.length;
        //现将数组排序
        Arrays.sort(nums);
        for (int i = 0; i < n; i++) {
            int first = nums[i];
            if (i > 0 && first == nums[i - 1]) continue;
            if (first > 0) break;
            int left = i + 1;
            int right = n - 1;
            while (left < n && left < right) {
                int second = nums[left];
                int third = nums[right];
                if (second + third == -first) {
                    List<Integer> list = new ArrayList<>();
                    list.add(first);
                    list.add(second);
                    list.add(third);
                    res.add(list);
                    //不可以重复
                    left++;
                    right--;
                    while (left < right && nums[left] == nums[left - 1]) left++;
                    while (left < right && nums[right] == nums[right + 1]) right--;
                } else if (second + third > -first) {
                    right--;
                    while (left < right && nums[right] == nums[right + 1]) right--;
                }
                else {
                    left++;
                    while (left < right && nums[left] == nums[left - 1]) left++;
                }
            }
        }
        return res;
    }

    @Test
    public void test() {
        int[] nums = {-1,0,1,2,-1,-4};
        List<List<Integer>> lists = threeSum(nums);
        System.out.println(lists);
    }
}
